<template>
 <div>
   <el-form :inline="true" :model="user" ref="ruleForm" class="demo-form-inline" :rules="rules">
     <el-form-item label="用户名" prop="username">
       <el-input v-model="user.username" placeholder="用户名"></el-input>
     </el-form-item>
     <el-form-item label="密码" prop="password">
       <el-input v-model="user.password" placeholder="密码" show-password></el-input>
     </el-form-item>
     <el-form-item label="验证码" prop="code">
       <el-input v-model="user.code" placeholder="验证码"></el-input>
       <el-image
           style="width: 100px; height: 100px"
           :src="url" @click="getCodeImg"
        ></el-image>
     </el-form-item>

     <el-form-item>
       <el-button type="primary" @click="login('ruleForm')">登录</el-button>
     </el-form-item>
   </el-form>
 </div>
</template>

<script>
export default {
  name: "LoginView",
  data() {
    return {
      user:{},
      url:'',
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
        ],
      }
    }
  }, methods: {
    //获取验证码
    getCodeImg(){
      let codeKey=Date.now();//时间戳
      this.user.codeKey=codeKey;//把codeKey 封装到user对象中
      this.url='http://localhost:9999/auth/getCodeImg?codeKey='+codeKey;
    },
    login(formName){

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios.post("http://localhost:9999/auth/login",this.user).then(res=>{
            if(res.data.code==200){
              sessionStorage.setItem("token",res.data.data);
              this.$message.success(res.data.msg);
              this.$router.push("/goods");
            }else{
              this.$message.error(res.data.msg);
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });



    }
  }, created() {
     this.getCodeImg();
  }
}
</script>

<style scoped>

</style>